package top.kikt.book.core.handlers

import org.jsoup.nodes.Document
import top.kikt.book.core.entity.BookMetaEntity
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler
import top.kikt.book.util.HttpUtils
import top.kikt.book.util.HttpUtils.string

/**
 * https://www.800book.net/56
 */
@Suppress("ClassName")
class `800Book` : BaseBookHandler() {

    override val host: String
        get() = "www.800book.net"

    override fun parseBookMeta(document: Document, url: String): BookMetaEntity {
        val name = document.select("h1").text()
        val author = document.select("#info p a").text()
        logger.info("name = $name, author = $author")

        return BookMetaEntity(name, url, url, author).apply {
            val cover = document.select("#fmimg img").attr("src") ?: return@apply
            this.coverImageUrl = cover
        }
    }

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val arrayList = ArrayList<ChapterMetaEntity>()

        val box = document.select(".box_con")[1][0][0]

        val two = box.select("dt")[1]
        var i = 0
        var start = false
        for (child in box.children()) {
            if (child == two) {
                start = true
                continue
            }

            if (!start) {
                continue
            }

            if (child.tagName() == "dt") {
                continue
            }

            val a = child.select("a")[0]
            val href = a.attr("href")
            val text = a.text()
            val url = "https://$host$href"

            logger.info("i = $i, text = $text, href = $href")

            val chapterMeta = ChapterMetaEntity(text, i, url, child)
            arrayList.add(chapterMeta)

            i++
        }

        return arrayList
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        val name = "第${chapterMetaEntity.index}章 ${chapterMetaEntity.name}"

        val doc = HttpUtils.get(chapterMetaEntity.url).string(charset)?.toDocument() ?: return null

        val content = doc.getElementById("content")!!

        val list = content.children().toMutableList().apply {
            removeLast()
        }

        val result = list.joinToString("\n") {
            it.wholeText()
        }

        return ChapterEntity(name, chapterMetaEntity.index, result)
    }

}
